package com.meritdata.cloud.data.standard.table.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.meritdata.cloud.data.base.ResultData;
import com.meritdata.cloud.data.standard.table.dao.IDictDirDao;
import com.meritdata.cloud.data.standard.table.dao.IDictModelDao;
import com.meritdata.cloud.data.standard.table.entity.TdDictDir;
import com.meritdata.cloud.data.standard.table.entity.TdDictModel;
import com.meritdata.cloud.data.standard.table.service.IDictDirService;

@Service
public class DictDirService implements IDictDirService {

	private static final Long ROOT_ID = 0L;

	@Autowired
	private IDictDirDao dictDirDao;

	@Autowired
	private IDictModelDao dictModelDao;

	@Override
	public ResultData create(String name, Long pid, String userId) {
		ResultData resultData = new ResultData();

		List<TdDictDir> dirs = dictDirDao.findHql("from TdDictDir t where t.name = ? and t.pid = ?", name, pid);
		if (!CollectionUtils.isEmpty(dirs)) {
			resultData.setStatus(false);
			resultData.setMsg("名称已存在");
			return resultData;
		}

		TdDictDir dir = new TdDictDir();
		dir.setName(name);
		dir.setPid(pid);
		dir.setCreator(userId);
		dir.setCreateTime(new Date());
		dictDirDao.save(dir);
		resultData.setData(dir);
		return resultData;
	}

	@Override
	public ResultData delete(Long id) {
		ResultData resultData = new ResultData();

		List<TdDictDir> dirs = dictDirDao.findEqualField("pid", id);
		if (!CollectionUtils.isEmpty(dirs)) {
			resultData.setStatus(false);
			resultData.setMsg("目录不为空");
			return resultData;
		}

		List<TdDictModel> dicts = dictModelDao.findEqualField("dirId", id);
		if (!CollectionUtils.isEmpty(dicts)) {
			resultData.setStatus(false);
			resultData.setMsg("目录不为空");
			return resultData;
		}

		resultData.setStatus(dictDirDao.delete(id) > 0);
		return resultData;
	}

	@Override
	public List<TdDictDir> tree() {
		List<TdDictDir> dirs = dictDirDao.findAll();
		List<TdDictDir> roots = new ArrayList<>();
		Map<Long, TdDictDir> dirMapping = new HashMap<>();
		for (TdDictDir dir : dirs) {
			dirMapping.put(dir.getId(), dir);
			if (dir.getPid() == ROOT_ID) {
				roots.add(dir);
			}
		}

		for (TdDictDir dir : dirs) {
			Long pid = dir.getPid();
			TdDictDir tdDictDir = dirMapping.get(pid);
			if (tdDictDir != null) {
				List<Object> children = tdDictDir.getChildren();
				if (children == null) {
					children = new ArrayList<>();
					tdDictDir.setChildren(children);
				}
				children.add(dir);
			}
		}

		return roots;
	}

}
